package com.shijunhao.graduation.handler.auth;

import com.alibaba.fastjson.JSON;
import com.shijunhao.graduation.domain.bean.ResultCode;
import com.shijunhao.graduation.domain.entity.SystemLoginLog;
import com.shijunhao.graduation.event.LoginLogEvent;
import com.shijunhao.graduation.utils.SystemLoginLogUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: shijunhao
 * @date: 2022/3/3 14:48
 * @description: 退出成功后置处理
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private final ApplicationEventPublisher applicationEventPublisher;
    private final SystemLoginLogUtils systemLoginLogUtils;

    @Autowired
    public LogoutSuccessHandlerImpl(ApplicationEventPublisher applicationEventPublisher, SystemLoginLogUtils systemLoginLogUtils) {
        this.applicationEventPublisher = applicationEventPublisher;
        this.systemLoginLogUtils = systemLoginLogUtils;
    }


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", MediaType.ALL.getSubtype());
        String msg = "退出成功";
        response.getWriter().write(JSON.toJSONString(ResultCode.success(msg)));
        SystemLoginLog loginLog = systemLoginLogUtils.getLoginLog(msg);
        loginLog.setUsername(authentication.getName());
        applicationEventPublisher.publishEvent(new LoginLogEvent(loginLog));
    }
}
